<?php

include_once '../info_struct.php';
include_once '../LDB_API/output.php';

/*
 * Usage:
 * create_list();
 * Parameter:
 * none but it requires the two Parameters 'from' and 'to' via GET
 * Return:
 * true if creation of list was successful
 * false if not
 * Also it prints out a list of the References in the Database starting
 * with the id 'from' to the id 'to'.
 */
function create_list() {
    if (!(array_key_exists('from', $_GET) && array_key_exists('to', $_GET))) {
        $from = 0;
        $to = 50;
    } else {
        $from = check_input($_GET['from']);
        $to = check_input($_GET['to']);
    }
    
    
    if (!(is_numeric($from) && is_numeric($to))) {
        echo "An error occurred!";
        return false;
    }
    
    if ($from < 0 || $to < 0 || $to < $from) {
        echo "An error occurred!";
        return false;
    }
    
    $dif = $to - $from;
    
    $refs = ldb_get_list();
    if (!$refs) {
        echo "An error occured!";
        return false;
    }
    
    echo "<table>";
    foreach ($refs as $ref) {
        if ($ref->id >= $from && $ref->id < $to) {
            echo "<td id='ref_$ref->id'>$ref->id</td>";
            echo "<td>";
            print_table_entry($ref);
            echo "</td>";
            echo "</tr>";
        }
    }
    echo "</table>";
    
    $count_lists = count($refs)/$dif;
    $last_id = array_pop($refs)->id;
    $j = 0;
    
    for (; $j <= $last_id; $j += $dif) {
        $k = $j + $dif;
        $ki = $k - 1;
        echo "<a href='./test_list.php/?from=". $j . "&to=" . $k
            ."'>$j - $ki</a>  ";
    }

    if ($j < $last_id) {
        echo "<a href='./test_list.php/?from=". $j . "&to=" . $last_id
        ."'>$j - $last_id</a>";
    }
    
}

function print_table_entry($ref) {
    
    if ($ref->author && strlen($ref->author) > 0) {
        echo $ref->author . "<br>";
    }
    if ($ref->title && strlen($ref->title) > 0) {
        echo "<i>$ref->title</i><br>";
    }
    if ($ref->year && strlen($ref->year) > 0) {
        echo $ref->year . "<br>";
    }
    if ($ref->note && strlen($ref->note) > 0) {
        echo $ref->note . "<br>";
    }
    if ($ref->journal && strlen($ref->journal) > 0) {
        echo $ref->journal . "<br>";
    }
    if ($ref->doi && strlen($ref->doi) > 0) {
        echo "<a href='http://dx.doi.org/$ref->doi'>DOI $ref->doi</a><br>";
    }
    if ($ref->zmath && strlen($ref->zmath) > 0) {
        echo "<a href='http://zbmath.org/?q=an:$ref->zmath'>
            ZMath $ref->zmath</a><br>";
    }
    if ($ref->arxiv && strlen($ref->arxiv) > 0) {
        echo "<a href='http://arxix.org/abs/$ref->arxiv'>
            arXiv $ref->arxiv</a><br>";
    }
}

function check_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    $data = mysql_real_escape_string($data);
    return $data;
}